<template>
	<div class="padding-container preview-wrap">
		<div class="title-part">
      <el-button size="mini" @click="toRefreshApps()"  type="primary" class="pull-right" v-show="showBtn">{{ $root.lang.control.device.detail.app.getApps }}</el-button>
      <el-button size="mini" @click="fetchData()"  type="primary" class="lang-select pull-right" v-show="showBtn">{{ $root.lang.control.device.detail.app.refresh }}</el-button>
		</div>
    <el-form ref="tableParams" :inline="true" :model="tableParams" size="small">
      <el-form-item :label="$root.lang.control.app.list.appName">
        <el-input v-model="tableParams.appName"></el-input>
      </el-form-item>
      <el-form-item :label="$root.lang.control.app.list.appVersion">
        <el-input v-model="tableParams.appVersion"></el-input>
      </el-form-item>
      <!-- <el-form-item :label="$root.lang.control.app.list.isPublic">
        <el-select v-model="tableParams.isPublic" :placeholder="$root.lang.control.app.list.select" clearable>
          <el-option :label="item.title" :value="item.value" :key="item.value" v-for="item in baseState.isPublic"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$root.lang.control.app.list.auditState">
        <el-select v-model="tableParams.auditState" :placeholder="$root.lang.control.app.list.select" clearable>
          <el-option :label="item.title" :value="item.value" :key="item.value" v-for="item in baseState.appAuditState"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$root.lang.control.app.list.delFlag">
        <el-select v-model="tableParams.delFlag" :placeholder="$root.lang.control.app.list.select">
          <el-option :label="item.title" :value="item.value" :key="item.value" v-for="item in baseState.delFlag"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$root.lang.control.app.list.appState">
        <el-select v-model="tableParams.appState" :placeholder="$root.lang.control.app.list.select" clearable>
          <el-option :label="item.title" :value="item.value" :key="item.value" v-for="item in baseState.appState"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" size="small" @click="searchAction()" >{{ $root.lang.control.app.list.query }}</el-button>
        <el-button size="small" @click="searchAction(true)" >{{ $root.lang.control.app.list.empty }}</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="listLoading"
      :data="appList"
      :empty-text="$root.lang.control.device.list.noData"
      size="small"
      border
      style="width: 100%"
      :header-cell-style="{'text-align':'center'}"
      >
      <el-table-column
        align="center"
        width="150"
        :label="$root.lang.control.device.detail.app.appName">
        <template slot-scope="scope">
          <span>{{ scope.row.appName | dataFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        width="150"
        :label="$root.lang.control.device.detail.app.appIdentification">
        <template slot-scope="scope">
          <span>{{ scope.row.appIdentification | dataFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$root.lang.control.device.detail.app.appVersion">
        <template slot-scope="scope">
          <span>{{ scope.row.appVersion | dataFormat}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        width="90"
        :label="$root.lang.control.device.detail.app.appV">
        <template slot-scope="scope">
          <span>{{ scope.row.appV | dataFormat}}</span>
        </template>
      </el-table-column>
      <el-table-column
        width="240"
        align="center"
        :label="$root.lang.control.device.detail.app.appMainClass">
        <template slot-scope="scope">
          <span>{{ scope.row.appMainClass | dataFormat}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$root.lang.control.device.detail.app.deviceType">
        <template slot-scope="scope">
          <p>{{ scope.row.typeName | dataFormat}}</p>
        </template>
      </el-table-column>
      <!-- <el-table-column
        width="150"
        align="center"
        :label="$root.lang.control.device.detail.app.appDesc">
        <template slot-scope="scope">
          <span>{{ scope.row.appDesc | dataFormat}}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        width="120"
        align="center"
        :label="$root.lang.control.device.detail.app.appSet">
        <template slot-scope="scope">
          <span v-if="scope.row.startNow == 1">{{ setType.operateType[3].setType.startNow.name }}</span>
          <span v-if="scope.row.autoStart == 1">{{ setType.operateType[3].setType.autoStart.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$root.lang.control.device.detail.app.appState">
        <template slot-scope="scope">
          <span >{{ baseState.appState, scope.row.appState,'--'| matchValue }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$root.lang.control.device.detail.app.isNative">
        <template slot-scope="scope">
          <span >{{ baseState.isNative, scope.row.isNative,'--'| matchValue }}</span>
        </template>
      </el-table-column>
      <el-table-column
        width="140"
        align="center"
        :label="$root.lang.control.device.detail.app.creTime">
        <template slot-scope="scope">
          <span>{{ scope.row.creTime | dateFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column
        width="140"
        align="center"
        :label="$root.lang.control.device.detail.app.installTime">
        <template slot-scope="scope">
          <span>{{ scope.row.installTime | dateFormat }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        width="140"
        align="center"
        :label="$root.lang.control.device.detail.app.uninstallTime">
        <template slot-scope="scope">
          <span>{{ scope.row.uninstallTime | dateFormat }}</span>
        </template>
      </el-table-column> -->
      <el-table-column 
        :width="operateWidth"
        :align="align"
        fixed="right"
        :label="$root.lang.control.device.list.operate">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="toDetail(scope.$index, scope.row)">{{ $root.lang.control.device.detail.app.detail }}</el-button>
          <el-button
            size="mini"
            type="warning"
            @click="toOperate(scope.$index, scope.row, 1)" v-show="showBtn">{{ $root.lang.control.device.detail.app.install }}</el-button>
          <el-button
            size="mini"
            type="success"
            @click="toOperate(scope.$index, scope.row, 2)" v-show="showBtn">{{ $root.lang.control.device.detail.app.run }}</el-button>
          <el-button
            size="mini"
            type="info"
            @click="toOperate(scope.$index, scope.row, 3)" v-show="showBtn">{{ $root.lang.control.device.detail.app.stop }}</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="toOperate(scope.$index, scope.row, 4)" v-show="showBtn">{{ $root.lang.control.device.detail.app.uninstall }}</el-button>
          <el-button
            size="mini"
            type="primary"
            @click="toEnableVisual(scope.$index, scope.row)" v-show="showBtn && scope.row.isNative == 0 && showVisual">
            {{ $root.lang.control.device.detail.app.enable }}</el-button>
          <el-button
            size="mini"
            type="primary"
            @click="toShowVisual(scope.$index, scope.row)" v-show="showBtn && scope.row.isNative == 0 && scope.row.webId != null">
            {{ $root.lang.control.device.detail.app.visual }}</el-button>
          <el-button
            size="mini"
            type="primary"
            @click="toShowLog(scope.$index, scope.row)" v-show="showBtn">{{ $root.lang.control.device.detail.app.log }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="tableTotal>0"
      @size-change="sizeChange"
      @current-change="pageChange"
      @prev-click="pageChange"
      @next-click="pageChange"
      :current-page="tableParams.pageNum"
      :page-sizes="[10, 30, 50, 100]"
      :page-size="tableParams.pageSize"
      layout="total, sizes, prev, pager, next"
      :total="tableTotal">
    </el-pagination>

    <AppSetting :show="showEdit" @editReceive="getReceive" @reload="reloadTable" />
	</div>
</template>

<script>
import AppSetting from './components/appSetting'
import '@/options/baseState'
import '@/options/taskState';
export default {
	name: 'DetailAppList',
  components: {
    AppSetting
  },
  props: {
    deviceId: {
      type: String,
      default: ''
    },
    baseData: {
      type: Object,
      default: null
    },
  },
	data() {
		return {
			listLoading:false,
      tableData:[],
      tableParams:{
        pageNum: 1,
        pageSize: 10,
        deviceId: this.deviceId,
        appVersion: null,
        appName: null,
        delFlag: 0,
        auditState: null,
        isPublic: null,
        deviceType: null,
        isInner: true
      },
      tableTotal:0,
      appList:null,
      baseState: {},
      setType: {},
      show: false,
      showBtn: true,
      showEdit: false,
      appId: null,
      showVisual: false,
      operateWidth: 580,
      align: 'left',
		}
	},
  computed: {

  },
  methods: {
    getReceive(data) {
      this[data.key] = data.value
    },
    reloadTable(data) {
      this.toInsatll(data)
    },
    checkLang() {
      let langType = this.$root.getStorage('lang')
      if(langType == 'en') {
        this.baseState = enBaseState
         this.setType = enSetType
      } else {
        this.baseState = baseState
         this.setType = setType
      }
    },
    sizeChange(val) {
      this.tableParams.pageNum = 1
      this.tableParams.pageSize = val
      this.fetchData()
    },
    pageChange(val) {
      this.tableParams.pageNum = val
      this.fetchData()
    },
    toDetail(index, row) {
      this.$router.push({ name:'PrivateDetail', params:{ id: row.id } })
    },
    toInsatll(data) {
      let devices = []
      let device = {
        deviceId: parseInt(this.deviceId)
      }
      devices.push(device)
      let param = {
        device: devices,
        appId: this.appId,
        operate: 1,
        startNow: data.startNow,
        autoStart: data.autoStart
      }
      this.toDo(param)
    },
    toOperate(index, row, type) {
      if(!this.checkState()) {
        return
      }
      // 安装应用
      if(type == 1) {
        if(!this.checkInstall(row.appState)) {
          return
        }
        this.showEdit = true
        this.appId = row.id
      } else {
        let confirmTip
        let confirm
        let cancel
        if(type == 2) {
          if(!this.checkRun(row.appState)) {
            return
          }
          confirmTip = this.$root.lang.confirm.runApp
          confirm = this.$root.lang.confirm.runImmediately
          cancel = this.$root.lang.confirm.noRun
        } else if(type == 3) {
          if(!this.checkStop(row.appState)) {
            return
          }
          confirmTip = this.$root.lang.confirm.stopApp
          confirm = this.$root.lang.confirm.stopImmediately
          cancel = this.$root.lang.confirm.noStop
        } else if(type == 4){
          if(!this.checkUninstall(row.appState)) {
            return
          }
          confirmTip = this.$root.lang.confirm.uninstallApp
          confirm = this.$root.lang.confirm.uninstallImmediately
          cancel = this.$root.lang.confirm.noUninstall
        }
        this.$confirm(confirmTip, this.$root.lang.confirm.tips, {
          confirmButtonText: confirm,
          cancelButtonText: cancel,
          type: 'warning'
        }).then(() => {
          let list = []
          let device = {
            deviceId: parseInt(this.deviceId)
          }
          list.push(device)
          let param = {
            device: list,
            appId: row.id,
            operate: type,
          }
          this.toDo(param)
        }).catch(() => {})
      }
    },
    toDo(param) {
      const loading = this.$loading({
        lock: true,
        text: this.$root.lang.confirm.process,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.request({
        url: '/application/issue',
        method: 'post',
        data: this.$root.optionProcess(param)
      }).then(response => {
        loading.close()
        this.$message({
          message: this.$root.lang.control.device.detail.operationTip,
          type: 'success',
          duration: 3 * 1000
        })
        this.searchAction(true)
      }).catch(error => {
        loading.close()
        this.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
    },
    toRefreshApps() {
      if(!this.checkState()) {
        return
      }
      this.$confirm(this.$root.lang.confirm.refreshApps, this.$root.lang.confirm.tips, {
        confirmButtonText: this.$root.lang.confirm.refreshAppsImmediately,
        cancelButtonText: this.$root.lang.confirm.noRefreshApps,
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: this.$root.lang.confirm.process,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        let devices = []
        let device = {
          deviceId: parseInt(this.deviceId)
        }
        devices.push(device)
        let param = {
          device: devices,
        }
        this.request({
          url: '/application/issue/update/app',
          method: 'post',
          data: param
        }).then(response => {
          loading.close()
          this.$message({
            message: this.$root.lang.control.device.detail.operationTip,
            type: 'success',
            duration: 3 * 1000
          })
        }).catch(error => {
          loading.close()
          this.$message({
            message: error.errmsg,
            type: 'error',
            duration: 3 * 1000
          })
        })
      }).catch(() => {})
    },
    refresh() {
      this.getDetail()
    },
    checkState() {
      if(this.baseData.isActivation != 3) {
        this.$message({
          message: this.$root.lang.control.device.detail.notActiveTip,
          type: 'error',
          duration: 3 * 1000
        })
        return false
      } else if(this.baseData.isConnection != 1) {
        this.$message({
          message: this.$root.lang.control.device.detail.notConnectTip,
          type: 'error',
          duration: 3 * 1000
        })
        return false
      } else if(this.baseData.isBinding != 2) {
        this.$message({
          message: this.$root.lang.control.device.detail.notBindTip,
          type: 'error',
          duration: 3 * 1000
        })
        return false
      } else {
        return true
      }
    },
    checkInstall(appState) {
      if(appState != 0) {
        let msg = ''
        if(appState == 5) {
          msg = '应用状态是安装中，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 6) {
          msg = '应用状态是已安装，已安装应用无需再安装，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 7) {
          msg = '应用状态是准备运行，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 8) {
          msg = '应用状态是停止中，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 9) {
          msg = '应用状态是卸载中，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 10) {
          msg = '应用状态是已运行，已安装应用无需再安装，请刷新，或更新应用记录刷新应用状态'
        }
        this.$message({
          message: msg,
          type: 'error',
          duration: 3 * 1000
        })
        return false
      } else {
        return true
      }
    },
    checkRun(appState) {
      if(appState != 6) {
        let msg = ''
        if(appState == 0) {
          msg = '应用状态是未安装，请先安装，或刷新，或更新应用记录刷新应用状态'
        } else if(appState == 5) {
          msg = '应用状态是安装中，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 7) {
          msg = '应用状态是准备运行，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 8) {
          msg = '应用状态是停止中，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 9) {
          msg = '应用状态是卸载中，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 10) {
          msg = '应用状态是已运行，已运行应用无需再运行，请刷新，或更新应用记录刷新应用状态'
        }
        this.$message({
          message: msg,
          type: 'error',
          duration: 3 * 1000
        })
        return false
      } else {
        return true
      }
    },
    checkStop(appState) {
      if(appState != 10) {
        let msg = ''
        if(appState == 0) {
          msg = '应用状态是未安装，未运行应用无需停止，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 5) {
          msg = '应用状态是安装中，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 6) {
          msg = '应用状态是已安装，未运行应用无需停止，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 7) {
          msg = '应用状态是准备运行，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 8) {
          msg = '应用状态是停止中，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 9) {
          msg = '应用状态是卸载中，请刷新，或更新应用记录刷新应用状态'
        } 
        this.$message({
          message: msg,
          type: 'error',
          duration: 3 * 1000
        })
        return false
      } else {
        return true
      }
    },
    checkUninstall(appState) {
      if(appState != 6) {
        let msg = ''
        if(appState == 0) {
          msg = '应用状态是未安装，未安装应用无需卸载，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 5) {
          msg = '应用状态是安装中，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 7) {
          msg = '应用状态是准备运行，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 8) {
          msg = '应用状态是停止中，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 9) {
          msg = '应用状态是卸载中，请刷新，或更新应用记录刷新应用状态'
        } else if(appState == 10) {
          msg = '应用状态是已运行，请先停止再卸载，或刷新，或更新应用记录刷新应用状态'
        }
        this.$message({
          message: msg,
          type: 'error',
          duration: 3 * 1000
        })
        return false
      } else {
        return true
      }
    },
    searchAction(reset) {
      if(reset) {
        this.tableParams = {
          pageNum: 1,
          pageSize: 10,
          deviceId: this.deviceId,
          appVersion: null,
          appName: null,
          delFlag: 0,
          auditState: null,
          isPublic: null,
          deviceType: null,
          isInner: true
        }
      } else {
        this.tableParams.pageNum = 1
      }
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      this.request({
          url: '/application/issue/page',
          method: 'post',
          data: this.$root.optionProcess(this.tableParams)
        }).then(response => {
          this.appList = response.rows
          this.tableTotal = response.total
          this.listLoading = false
        }).catch(error => {
          this.appList = []
          this.listLoading = false
      })
    },
    toEnableVisual(index, row) {
      this.$confirm(this.$root.lang.confirm.enableVisual, this.$root.lang.confirm.tips, {
        confirmButtonText: this.$root.lang.confirm.enableImmediately,
        cancelButtonText: this.$root.lang.confirm.noEnable,
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: this.$root.lang.confirm.process,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.request({
          url: '/web/dev-bid',
          method: 'get',
          params: {
            devId: this.deviceId,
            appId: row.id
          }
        }).then(response => {
          loading.close()
          this.$message({
            message: this.$root.lang.control.device.detail.operationTip,
            type: 'success',
            duration: 3 * 1000
          })
          this.searchAction(true)
        }).catch(error => {
          loading.close()
          this.$message({
            message: error.errmsg,
            type: 'error',
            duration: 3 * 1000
          })
        })
      }).catch(() => {})
    },
    toShowVisual(index, row) {
      window.open(this.Options.links.visual + 'show' + '?A=' + this.store.getters.status + '&M=' + this.baseData.imei + '&N=' + row.appIdentification
        + '&E=' + row.appSupplier + '&V=' + row.appV + '&D=' + this.deviceId + '&P=' + row.id + '&W=' + row.webId)
    },
    toShowLog(index, row) {
      if(this.Cookies.get('L') != 3) {
        this.$message({
          message: this.$root.lang.control.device.detail.app.logTip,
          type: 'warning',
          duration: 3 * 1000
        })
      }
      this.$router.push({ name:'DeviceAppLog', query:{ a: row.id, d: this.deviceId, m: this.baseData.imei, i:row.appIdentification, v: row.appV, e: row.appSupplier } })
    }
  },
  created() {
    this.showVisual = this.Cookies.get('V') == 3 ? true : false
    if(this.showVisual) {
      this.operateWidth = 580
    } else {
      this.operateWidth = 450
    }
    if(this.Cookies.get('T') == '2') {
			this.show = true
      if(this.Cookies.get('O') == '1') {
        // this.showBtn = false
        this.showBtn = true
        this.align = 'center'
        this.operateWidth = 580
      }
		} 
    this.fetchData()
    this.checkLang()
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
	.padding-container {
		text-align: left;
		.title-part {
			text-align: left;
			font-size: 16px;
			padding-bottom: 30px;
		}
    .lang-select {
      margin-right: 10px;
      cursor: pointer;
    }
	}
</style>